package com.cowmooed.interceptor;

import com.cowmooed.entity.SysUser;
import com.cowmooed.service.SysUserService;
import com.cowmooed.utils.AuthUtil;
import com.cowmooed.utils.BaseContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT认证拦截器
 * 用于拦截请求并验证JWT令牌的有效性
 */
@Component
@Slf4j
public class JwtAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private AuthUtil authUtil;
    
    @Autowired
    private SysUserService sysUserService;

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     * 验证JWT令牌的有效性
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的Authorization字段
        String authHeader = request.getHeader("Authorization");
        log.debug("拦截请求: {}", request.getRequestURI());
        log.debug("Authorization Header: {}", authHeader);


        // OPTIONS 预检请求直接放行
        if ("OPTIONS".equals(request.getMethod())) {
            log.debug("OPTIONS预检请求，直接放行: {}", request.getRequestURI());
            return true;
        }

        // 如果是登录或注册等公开接口，直接放行
        if (isPublicApi(request.getRequestURI())) {
            log.debug("公开接口，直接放行: {}", request.getRequestURI());
            return true;
        }

        // 检查Authorization头是否存在且格式正确
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            log.warn("请求头中缺少有效的Authorization字段: {}", request.getRequestURI());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\": 401, \"msg\": \"请先完成登录或注册操作\"}");
            return false;
        }

        // 提取JWT令牌
        String token = authUtil.getJwtFromHeader(authHeader);

        // 验证令牌的有效性
        if (!authUtil.validateToken(token)) {
            log.warn("无效的JWT令牌: {}", request.getRequestURI());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\": 401, \"msg\": \"无效的令牌\"}");
            return false;
        }

        // 从令牌中提取用户名并设置到请求属性中
        String username = authUtil.getUsernameFromToken(token);
        request.setAttribute("currentUser", username);
        
        // 根据用户名查询用户信息，设置用户ID到ThreadLocal中
        try {
            SysUser user = sysUserService.findByUserName(username);
            if (user != null) {
                BaseContextUtil.setCurrentId(user.getUserId());
                log.debug("用户 {} (ID: {}) 认证成功", username, user.getUserId());
            }
        } catch (Exception e) {
            log.error("设置用户ID失败: {}", e.getMessage());
        }

        return true;
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 可以在这里添加请求处理后的逻辑
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet渲染了对应的视图之后执行
     * 主要用于资源清理工作
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 可以在这里添加资源清理的逻辑
    }

    /**
     * 判断是否为公开接口
     * @param uri 请求URI
     * @return 是否为公开接口
     */
    private boolean isPublicApi(String uri) {
        return uri.contains("/backcode/auth/") ||
               uri.contains("/backcode/swagger") ||
               uri.contains("/backcode/webjars/") ||
               uri.contains("/backcode/v2/api-docs") ||
               uri.contains("/backcode/v3/api-docs") ||
               uri.contains("/backcode/favicon.ico") ||
               uri.contains("/backcode/error");
    }
}